#include "CRandom.h"
#include "Box2D\Box2D.h"
#include "CCStdC.h"
CRandom::CRandom()
{
	b2Timer t;
	SetSeed(std::rand());	
	//std::lo
}

CRandom::CRandom(unsigned long seed)
{
	SetSeed(seed);
}

void CRandom::SetSeed(unsigned long seed)
{
	m_Val[0] = seed;
	for (m_iRandomIndex = 1; m_iRandomIndex < RND_C; m_iRandomIndex++)
	{
		m_Val[m_iRandomIndex] = (Mult(RND_B, m_Val[m_iRandomIndex - 1])) & RND_MAX_VAL_MASK;
	}
}

unsigned int CRandom::NextInt(unsigned int max)
{
	m_iRandomIndex = (m_iRandomIndex + 1) % RND_C;
	int shift1 = (m_iRandomIndex + (RND_C - 1) - RND_B) % RND_C;
	int shift2 = (m_iRandomIndex + (RND_C - 1)) % RND_C;

	m_Val[m_iRandomIndex] = (m_Val[shift1] + m_Val[shift2]) & RND_MAX_VAL_MASK;
	unsigned long rint = ((m_Val[m_iRandomIndex] >> RND_HALF_MAX_VAL_SHIFT)*max) >> RND_HALF_MAX_VAL_SHIFT;
	return unsigned int(rint);
}

unsigned int CRandom::NextTrueFalse()
{
	return  NextInt(100) > 50?1:0;
}

unsigned int CRandom::NextTrue(unsigned int percent)
{
	return NextInt(100) < percent?1:0;
}

unsigned long CRandom::Mult(unsigned long a, unsigned long b) // mul 2 number without overflow. Assume a, b are 30bits integers.
{
	unsigned long a1 = a>>RND_HALF_MAX_VAL_SHIFT;
	unsigned long a0 = a&RND_HALF_MAX_VAL_MASK;
	unsigned long b1 = b>>RND_HALF_MAX_VAL_SHIFT;
	unsigned long b0 = b&RND_HALF_MAX_VAL_MASK;

	unsigned long mul = (((((a0*b1) + (a1*b0)) & RND_HALF_MAX_VAL_MASK) << RND_HALF_MAX_VAL_SHIFT) + a0*b0) & RND_MAX_VAL_MASK;

	return mul;
}
